package com.jlnk.androidfmc.view;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.appcompat.app.AppCompatActivity;

import com.jlnk.androidfmc.R;
import com.jlnk.androidfmc.database.PostDatabase;
import com.jlnk.androidfmc.entity.Post;
import com.jlnk.androidfmc.fragment.HotNewFragment;
import com.jlnk.androidfmc.fragment.fragments.FarmerCircleFragment;

import java.io.ByteArrayOutputStream;

public class NyqPost extends AppCompatActivity {

    private EditText contentEditText;
    private ImageView selectedImage;
    private Button postButton, buttonChooseImage;
    private PostDatabase db;
    private byte[] imageBytes; // 存储图片字节数组

    static final int PICK_IMAGE_REQUEST = 1;
    private ActivityResultLauncher<Uri> imagePickerLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nyq_post); // 加载XML布局文件

        // 初始化UI组件
        contentEditText = findViewById(R.id.contentEditText);
        selectedImage = findViewById(R.id.selectedImage);
        postButton = findViewById(R.id.postButton);
        buttonChooseImage = findViewById(R.id.buttonChooseImage);

        // 初始化数据库实例
        db = PostDatabase.getInstance(this);
        checkAndRefreshPosts(getIntent());

        // 设置返回按钮的点击事件
        ImageButton btnBack = findViewById(R.id.btnBack);
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish(); // 结束当前Activity
            }
        });

        // 设置选择图片按钮的点击事件
        buttonChooseImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openImagePicker(); // 打开图片选择器
            }
        });

        // 设置发布按钮的点击事件
        postButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取用户输入的内容
                String content = contentEditText.getText().toString();
                if (content.isEmpty() || imageBytes == null) {
                    Toast.makeText(NyqPost.this, "内容和图片不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 将Bitmap转换为字节数组
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        long result = db.insertPost(content, imageBytes); // 插入帖子到数据库
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (result != -1) {
                                    Toast.makeText(NyqPost.this, "发布成功", Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(NyqPost.this, MyNyq.class);
                                    intent.putExtra("REFRESH_POSTS", true);
                                    startActivity(intent);
                                    setResult(RESULT_OK, intent); // 设置结果
                                    finish(); // 结束当前Activity
                                } else {
                                    Toast.makeText(NyqPost.this, "发布失败", Toast.LENGTH_SHORT).show(); // 显示发布失败消息
                                }
                            }
                        });
                    }
                }).start(); // 启动线程
            }
        });
    }
    // 检查Intent并刷新帖子列表

    private void checkAndRefreshPosts(Intent intent) {
        if (intent != null && intent.getBooleanExtra("REFRESH_POSTS", false)) {
            refreshPosts();
        }
    }

    // 刷新帖子列表的方法
    private void refreshPosts() {
        // 实现刷新逻辑
    }


    // 打开图片选择器
    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }

    // 处理图片选择结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
                selectedImage.setImageBitmap(bitmap);
                // 转换Bitmap为字节数组
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                imageBytes = outputStream.toByteArray();
                // 这里您可以根据需要调整图片压缩质量和格式
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "图片加载失败", Toast.LENGTH_SHORT).show();
            }
        }

    }
}